package controller

import (
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	"gorm.io/gorm/clause"
	"mygo/app/models"
	"mygo/app/tools"
	"strings"
	"time"
)

type tide_ctl struct {
	db *gorm.DB
}

var Tide = tide_ctl{}

// SaveTideData 保存潮汐数据
func (ctl *tide_ctl) SaveTideData(c *gin.Context) {
	var tideList []models.TideHourNew
	c.ShouldBind(&tideList)
	//遍历tideList，将SaveDate设为当前时间 格式为 2021-01-01
	for i := range tideList {
		tideList[i].SaveDate = time.Now().Format("2006-01-02")
	}
	ctl.db = models.Db
	mm.Lock()
	models.Db.Clauses(clause.OnConflict{
		Columns:   []clause.Column{{Name: "idx_date_time_station"}},
		DoUpdates: clause.AssignmentColumns([]string{"tide"}),
	}).Create(&tideList)
	mm.Unlock()
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "success",
	})
}

func (ctl *tide_ctl) GetTwcListNew(c *gin.Context) {
	ctl.db = models.Db
	dateStart := c.Query("dateStart")
	dateEnd := c.Query("dateEnd")
	station := c.Query("station")
	//转为字符串数组
	stationList := strings.Split(station, ",")
	var twcList []models.TideHourNew

	//获取时间范围内，station在stationList中的数据
	ctl.db.Where("date >= ? AND date <= ? AND station IN (?)", dateStart, dateEnd, stationList).Find(&twcList)
	tools.SuccessResp(c, "获取成功", twcList)
}

func (ctl *tide_ctl) GetTwcListNewW(c *gin.Context) {
	ctl.db = models.Db
	var twcList []models.TideHourNew
	//根据SaveDate分组，获取最新日期下的所有数据
	ctl.db.Find(&twcList)
	tools.SuccessResp(c, "获取成功", twcList)
}
